package leetcode.code0155;

import java.util.Stack;

public class MinStack1 extends Solution155 {

	private Stack<Integer> s;
	private int min;

	public MinStack1() {
		s = new Stack<>();
		min = Integer.MAX_VALUE;
	}

	public void push(int val) {
		if (val < min)
			min = val;
		s.push(val);
	}

	public void pop() {
		int m = s.pop();
		if (m == min) {
			min = Integer.MAX_VALUE;
			Stack<Integer> t = new Stack<>();
			while (!s.isEmpty()) {
				int cur = s.pop();
				min = cur < min ? cur : min;
				t.add(cur);
			}
			while (!t.isEmpty()) {
				s.add(t.pop());
			}
		}
	}

	public int top() {
		return s.peek();
	}

	public int getMin() {
		return min;
	}

	public static void main(String[] args) {
		MinStack1 minStack = new MinStack1();
		minStack.push(1);
		minStack.push(2);
		int s = minStack.top();
		System.out.println(s);
		s = minStack.getMin();
		System.out.println(s);
		minStack.pop();
		s = minStack.getMin();
		System.out.println(s);
		s = minStack.top();
		System.out.println(s);
	}

}
